package com.novellotus.iov.carvice.model;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.ModifyMobileActivity;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.Response;

/**
 * Created by Rich on 2017/8/8.
 */

public class ModifyMobileModel {

    private ModifyMobileActivity context;
    private Observable<CharSequence> ObservablePhone;
    private Observable<CharSequence> ObservableCode;
    private final int MAX_COUNT = 60;

    public ModifyMobileModel(ModifyMobileActivity context) {
        this.context = context;

    }


    /**
     * 设置手机号码编辑框
     */
    public void setMobileEditText(final EditText mobile, final Button code, final String id) {
        ObservablePhone = RxTextView.textChanges(mobile);
        ObservablePhone.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .compose(RxSchedulers.<CharSequence>compose())
                .switchMap(new Function<CharSequence, ObservableSource<Boolean>>() {
                    @Override
                    public ObservableSource<Boolean> apply(final CharSequence phone) throws Exception {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                if (MyUtils.isMobile(phone.toString())) {
                                    Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().validMobile(phone.toString(), "update_info"


                                    );
                                    observable.compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                                            .subscribe(new BaseObserver<Boolean>(context) {
                                                @Override
                                                public void onSuccess(Boolean response) {
                                                    if (!response) {
                                                        MyUtils.showToast(context, "手机号已注册");
                                                    }
                                                    e.onNext(response);
                                                }

                                                @Override
                                                public void onFail(int code, String msg) {
                                                    MyUtils.showToast(context, msg);
                                                    e.onNext(false);
                                                }

                                                @Override
                                                public void onError(String msg) {
                                                    MyUtils.showToast(context, msg);
                                                }
                                            });

                                } else {
                                    if (phone.length() == 11) {
                                        MyUtils.showToast(context, "手机号码不正确");
                                    }
                                    e.onNext(false);
                                }
                            }
                        });
                    }
                }).subscribe(new MyObserver<Boolean>() {
            @Override
            public void onNext(Boolean pass) {
                super.onNext(pass);
                if (pass) {
                    mobile.setTextColor(context.getResources().getColor(R.color.text_black));
                    code.setClickable(true);
                    code.setTextColor(context.getResources().getColor(R.color.btn_can_click_color));
                } else {
                    mobile.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                    code.setTextColor(context.getResources().getColor(R.color.btn_can_not_click_color));
                    code.setClickable(false);
                }
            }
        });
    }


    /**
     * 设置验证码编辑框
     */
    public void setCode(final EditText code) {
        ObservableCode = RxTextView.textChanges(code);
        ObservableCode.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                if (value.length() == 6) {
                    code.setTextColor(context.getResources().getColor(R.color.text_black));
                } else {
                    code.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                }
            }
        });
    }


    /**
     * 设置发送短信按钮
     * 倒计时60s
     */
    private Disposable disposables;
    private Observable<Long> mObservableCountTime;
    private Button btnCode;
    private EditText edtCode;

    public void setBtnCode(final Button btnCode, final EditText editText) {
        this.btnCode = btnCode;
        this.edtCode = editText;
        mObservableCountTime = RxView.clicks(btnCode).compose(RxSchedulers.lifecycle(context)).throttleFirst(MAX_COUNT, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).flatMap(new Function<Object, ObservableSource<Long>>() {
            @Override
            public ObservableSource<Long> apply(Object o) throws Exception {
                //点击后设置按钮的状态
                btnCode.setClickable(false);
                btnCode.setTextColor(context.getResources().getColor(R.color.btn_can_not_click_color));

                //请求短信接口
                final Observable<BaseEntity<Response>> observable = RetrofitFactory.getInstance().sendSms(editText.getText().toString());
                observable.compose(RxSchedulers.<BaseEntity<Response>>lifecycle(context))
                        .compose(RxSchedulers.<BaseEntity<Response>>compose())
                        .subscribe(new BaseObserver<Response>(context) {
                            @Override
                            public void onSuccess(Response response) {

                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);
                                disposables.dispose();
                                disposables = mObservableCountTime.subscribe(timeConsumer);
                                btnCode.setTextColor(context.getResources().getColorStateList(R.color.selector_black_blue));
                                btnCode.setClickable(true);
                                btnCode.setText("发送验证码");
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, "发送短信失败,请稍后重试");
                                disposables.dispose();
                                disposables = mObservableCountTime.subscribe(timeConsumer);
                                btnCode.setTextColor(context.getResources().getColorStateList(R.color.selector_black_blue));
                                btnCode.setClickable(true);
                                btnCode.setText("发送验证码");
                            }

                        });

                return Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).take(MAX_COUNT);
            }
        });

        disposables = mObservableCountTime.subscribe(timeConsumer);
        btnCode.setClickable(false);
    }

    Consumer<Long> timeConsumer = new Consumer<Long>() {
        @Override
        public void accept(Long aLong) throws Exception {
            //显示剩余时长。当倒计时为 0 时，还原 btn 按钮.
            if (MAX_COUNT - (aLong + 1) == 0) {
                btnCode.setTextColor(context.getResources().getColorStateList(R.color.selector_black_blue));
                btnCode.setClickable(true);
                btnCode.setText("发送验证码");
            } else {
                btnCode.setText(MAX_COUNT - (aLong + 1) + "s");
            }

        }
    };

    /**
     * 表单验证
     */
    public void setConfirm(final Button btn_right) {
        Observable.combineLatest(ObservablePhone, ObservableCode, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence phone, CharSequence code) throws Exception {

                return phone.length() == 11 && MyUtils.isMobile(phone.toString()) && code.length() == 6;
            }
        }).compose(RxSchedulers.<Boolean>lifecycle(context)).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    btn_right.setTextColor(context.getResources().getColorStateList(R.color.white));
                } else {
                    btn_right.setTextColor(context.getResources().getColor(R.color.gray_line));
                }
            }
        });
    }


    /**
     * 修改手机号
     */
    public void changeMobile(TextView textView, final EditText mobile, final EditText code) {
        //  "mobile":"182XXXXX","checkCode":"62763"}
        RxView.clicks(textView).compose(RxSchedulers.lifecycle(context)).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                JSONObject requestData = new JSONObject();
                try {
                    requestData.put("mobile", mobile.getText().toString());
                    requestData.put("checkCode", code.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().changeMobile(DataSign.getSign(requestData.toString(), context));
                observable.compose(RxSchedulers.<BaseEntity<Boolean>>lifecycle(context)).compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                        .subscribe(new BaseObserver<Boolean>(context) {
                            @Override
                            public void onSuccess(Boolean response) {
                                SharedPreferencesUtils.changeMobile(mobile.getText().toString(), context);
                                MyUtils.showToast(context, "修改成功!");
                                context.finish();
                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, msg);
                            }
                        });
            }
        });

    }
}
